/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.server;

import java.io.ByteArrayInputStream;   
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.validator.GenericValidator;
import org.mags.common.EngineContext;
import org.mags.remas.logic.EntityFileUtils;
import org.mags.remas.model.entity.EntityFile;
import org.mags.remas.model.entity.EntityRelationship;
import org.w3c.tidy.Tidy;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class DocumentServlet extends AbstractServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void doAction(HttpServletRequest req, HttpServletResponse resp)
		throws Exception {
		String id = req.getParameter("documentId");
		if(GenericValidator.isBlankOrNull(id))
			throw new RuntimeException("document not found");
		long lId = 0;
		try {
			lId = Long.parseLong(id);
		} catch(Exception e) {
			throw new RuntimeException("error in document id");
		}
		final EntityRelationship document =  EngineContext.getDataContext().getEntityProviderFactory().getEntityRelationshipProvider().getById(lId);
		if(document==null)
			throw new RuntimeException("document not found");
		List<EntityFile> files = EntityFileUtils.getFiles(document.getEntity().getEntityId());
		String htmlText = "";
		if(files.size()>0) 
			htmlText = new String(files.get(0).getRawContent());
		resp.setCharacterEncoding("utf-8");
		ByteArrayInputStream a = new ByteArrayInputStream(htmlText.getBytes());
		Tidy tidy = new Tidy();
		tidy.setQuiet(true);
		tidy.setShowWarnings(false);
		tidy.setForceOutput(true);		
		tidy.setXHTML(true);
		tidy.parse(a, resp.getOutputStream());
		resp.flushBuffer();
		resp.getOutputStream().close();
	}
}
